/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package heart_0812025;
import java.io.*;
import java.net.*;
/**
 *
 * @author Administrator
 */
public class Server {

    public final static int SERVERPORT = 1772;
    private static DatagramSocket serverds;
    public static String ID;
    public static String status;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            serverds = new DatagramSocket(SERVERPORT);
            HejImServer hello = new HejImServer(serverds);
            hello.start();
            while(true) {

            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

}
class HejImServer extends Thread{
        
        public String MSG_SERVER_IDENTIFY = "#I am server";
        public String MSG_CLIENT_FIND_SERVER = "#are you server ?";
        private DatagramSocket serverds;
        private byte[] buffer;
        public final static int BUFFER_SIZE = 1024;
        public final static int CLIENTPORT = 1775;
        private DatagramPacket pkdp;

        HejImServer(DatagramSocket ds) {
                serverds = ds;
	}

	public void run() {
            try {
                byte[] response = MSG_SERVER_IDENTIFY.getBytes();
                byte[] phong_res = Server.ID.getBytes();
                byte[] status_res = Server.status.getBytes();
                buffer = new byte[BUFFER_SIZE];
                pkdp = new DatagramPacket(buffer, BUFFER_SIZE);
                DatagramPacket outpkdp = new DatagramPacket(response, response.length, InetAddress.getByName("192.168.0.255"), CLIENTPORT);
                serverds.send(outpkdp);
                while (true) {
                    serverds.receive(pkdp);
                    String mess = new String(buffer);

                    // If this message is from a client, who doesn't know that you are a server
                    // tell him know!
                    if (mess.contains(MSG_CLIENT_FIND_SERVER)) {
                        //System.out.printf("Request SERVER from IP: %s\n",pkdp.getAddress().getHostAddress());

                        // Hey, I'm server.
                        DatagramPacket outpkdp1 = new DatagramPacket(response, response.length, pkdp.getAddress(), CLIENTPORT);
                        DatagramPacket outpkdp2 = new DatagramPacket(phong_res, phong_res.length, pkdp.getAddress(), CLIENTPORT);
                        DatagramPacket outpkdp3 = new DatagramPacket(status_res, status_res.length, pkdp.getAddress(), CLIENTPORT);
                        serverds.send(outpkdp1);
                        serverds.send(outpkdp2);
                        serverds.send(outpkdp3);
                    }
                }
            } catch (IOException ex) {

            }
	}
}
